import { cloneDeep } from 'lodash-es';
import { RouteObject } from 'react-router-dom';
import { create } from 'zustand';
import { devtools } from 'zustand/middleware';

import { fetchAuths } from '@/api/system';
import { RouteModel } from '@/models/RouteModel';
import { getUserRoutes } from '@/router';

export interface RouterStore {
  buttonKeys: Record<string, string[]>;
  firstPath: string;
  userAuths: RouteModel[];
  userRoutes: RouteObject[];
  loading: boolean;
  menus: RouteModel[];
  clear: () => void;
  getUserAuths: () => void;
  setLoading: (status: boolean) => void;
}

const useRouterStore = create<RouterStore>()(
  devtools(set => ({
    buttonKeys: {},
    loading: false,
    menus: [],
    firstPath: '',
    userAuths: [],
    userRoutes: [],
    clear: () => {
      set({ firstPath: '', menus: [], userAuths: [], userRoutes: [] });
    },
    getUserAuths: async () => {
      try {
        set({ loading: true });
        const {
          data: { buttonKeys, menuTree },
        } = await fetchAuths();
        const [userRoutes, firstPath] = getUserRoutes(menuTree);
        const menus = cloneDeep(menuTree).filter(deepFilterHidden);
        set({ buttonKeys, firstPath, loading: false, menus, userAuths: menuTree, userRoutes });
      } catch {
        set({ loading: false });
      }
    },
    setLoading: (status: boolean) => set({ loading: status }),
  }))
);

export default useRouterStore;

/**
 * 递归过滤掉除路由之外的数据
 * Tips: 此操作会改变数据源的children
 * @param item 权限数据
 * @returns true/false
 */
export const deepFilterHidden = (item: RouteModel) => {
  if (item?.children?.length) {
    item.children = item.children.filter(deepFilterHidden);
  }

  return !item.hidden;
};
